import urls from './urls';
import wepy from 'wepy';

/**
 * 把数据转换成x-www-form-urlencoded数据格式
 * @param {} element  数据
 * @param {*} key 
 * @param {*} list 
 */
function JSON_to_URLEncoded(element, key, list) {
    var list = list || [];
    if (typeof element == 'object') {
        for (var idx in element)
            JSON_to_URLEncoded(
                element[idx],
                key ? key + '[' + idx + ']' : idx,
                list
            );
    } else {
        list.push(key + '=' + encodeURIComponent(element));
    }
    return list.join('&');
}

/**
 * 获取微信用户数据
 * @param {*} cb 获取微信数据回调成功
 */
function getUserInfo(cb) {
    wx.getStorage({
        key: 'wx_user_info',
        success(res) {
            cb && cb(res.data);
        },
        fail() {
            wx.login({
                success(res) {
                    var code = res.code;
                    wx.request({
                        url: urls.login_for_user_info,
                        data: {
                            code: code,
                            appId: 'wxda2829f74ae77059'
                        },
                        success(res) {
                            wx.setStorage({
                                key: 'wx_user_info',
                                data: res.data.result,
                                success() {
                                    cb && cb(res.data.result)
                                }
                            })
                        }
                    });

                }
            })
        }
    })
}

function _showToast() {
    var options = {
        title: '加载中...',
        icon: 'loading',
        duration: 10000000
    };
    wepy.showToast(options);
}

function $post(options) {
    if (!options.header) {
        options.header = { 'content-type': 'application/x-www-form-urlencoded' };
    }
    if (options.data) {
        options.data = JSON_to_URLEncoded(options.data);
    }
    if (options.useLoading) {
        // 是否使用加载modal
        _showToast();
        var completeAction = options.complete;
        options.complete = () => {
            completeAction && completeAction();
            wx.hideToast();
        }
    }

    options.method = 'post';
    wx.request(options);
}

function $get(options) {
    if (!options.header) {
        options.header = { 'content-type': 'application/x-www-form-urlencoded' };
    }
    // if (options.data) {
    //     options.data = JSON_to_URLEncoded(options.data);
    // }
    if (options.useLoading) {
        // 是否使用加载modal
        _showToast();
        var completeAction = options.complete;
        options.complete = () => {
            completeAction && completeAction();
            wx.hideToast();
        }
    }
    wx.request(options);
}

export default {
    to_URLEncoded: JSON_to_URLEncoded,
    getUserInfo: getUserInfo,
    $post: $post,
    $get: $get
}